<template>
  <!--申请回收操作-->
  <div class="button_group">
    <el-button icon="EditPen" type="primary" @click="handleOpenDialog()">发起申请</el-button>
    <!--筛选，下拉框-->
    <el-button icon="Operation" style="margin:0px 10px" @click="handleOpenFilterDialog()">范围筛选</el-button>
  </div>
  <!--时间线申请回收任务列表-->
  <div class="request_group_list">
    <el-timeline style="max-width: 90%" v-if="pageKeys.length > 0">
      <el-timeline-item v-for="key in pageKeys" size="large" type="primary" :timestamp="key" placement="top">
        <!--垃圾回收申请列表【间隔】-->
        <el-space wrap style="width: 100%">
          <el-card v-if="pageData[key].length > 0" v-for="main in pageData[key]" :key="main"
            style="width: 245px; height: 250px" @click="handleOpenDialog(main.id)" shadow="hover">
            <template #header>预计收益:
              <span style="margin:0 5px;font-size:16px">{{ main.expectReturn }}</span>
              元</template>
            <template #default>
              <el-image v-if="getFirstUrl(main.wasteList)" style="
                  width: 200px;
                  height: 100px;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                " :src="getFirstUrl(main.wasteList)" fit="contain" />
              <!--图片缺省页-->
              <el-empty v-else :image-size="50" style="height: 100px">
                <template #description>
                  <span style="color: #909399">暂无图片</span>
                </template>
              </el-empty>
            </template>
            <template #footer>
              <div style="display: flex;justify-content: space-between">
                <el-tag :type="RecycleStatusOptions.find((item) => item.value === main.status)?.type">
                  {{RecycleStatusOptions.find((item) => item.value === main.status)?.label}}
                </el-tag>

                <el-link v-if="main.status == '3' || main.status == '9'" @click.stop="openHistoryRecord(main.id)"
                  type="primary">处理记录</el-link>
              </div>
            </template>
          </el-card>
          <!--数据缺省页-->
          <el-card v-else style="width: 245px; height: 250px">
            <el-empty :image-size="50" style="height: 100px">
              <span style="color: #909399">暂无数据</span>
            </el-empty>
          </el-card>
        </el-space>
      </el-timeline-item>
    </el-timeline>
    <el-empty v-else :image-size="200"></el-empty>
  </div>
  <!--发起申请弹框-->
  <el-dialog v-model="dialog.visible" :title="dialog.title" align-center width="700px" @close="handleCloseDialog"
    style="padding: 10px 20px">
    <el-form ref="dataFormRef" :model="formData" :rules="dataFormRules" label-width="100px" v-loading="formLoading">
      <el-form-item label="垃圾列表" v-if="formData.wasteList.length">
        <div style="display: flex; flex-direction: column">
          <el-scrollbar max-height="270px">
            <!--垃圾列表（图片、类型、重量）-->
            <el-space fill style="margin-bottom: 10px">
              <div v-for="(waste, index) in formData.wasteList" :key="index">
                <el-space>
                  <!-- 上传图片 -->
                  <el-image :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[waste.fileUrl]"
                    style="width: 100px; height: 80px" :src="waste.fileUrl" fit="cover" />

                  <!-- 垃圾类型选择 -->
                  <el-space direction="vertical" alignment="start" :size="10">
                    <el-space>
                      <el-select filterable v-model="waste.typeId" placeholder="请选择垃圾类型" style="width: 200px" disabled>
                        <el-option v-for="item in wasteTypesOptions" :key="item.id" :label="item.typeName"
                          :value="item.id" />
                      </el-select>
                      <el-input-number v-model="waste.weight" :precision="2" :step="0.1" placeholder=""
                        style="width: 200px" disabled>
                        <template #suffix>千克(kg)</template>
                      </el-input-number>
                    </el-space>
                    <el-space>
                      回收收益:
                      <el-text style="padding-left:10px">
                        {{ waste.actualPrice ? `${waste.actualPrice}元` : '待计算' }}
                      </el-text>
                    </el-space>
                  </el-space>

                </el-space>
              </div>
            </el-space>
          </el-scrollbar>

        </div>
      </el-form-item>
      <el-form-item label="回收地址" prop="address">
        <el-cascader size="large" :options="pcaTextArr" v-model="formData.area"
          :disabled="!judgeCanEdit(formData.status)"></el-cascader>
        <el-input v-model="formData.address" placeholder="详细地址" style="margin-left: 10px; height: 40px; width: 300px"
          :disabled="!judgeCanEdit(formData.status)"></el-input>
      </el-form-item>
      <el-form-item label="预约时间" prop="recycleTime">
        <el-date-picker v-model="formData.recycleTime" type="datetime" placeholder="预约时间" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss" :disabled="!judgeCanEdit(formData.status)"></el-date-picker>
      </el-form-item>
      <el-form-item label="联系方式" prop="mobile">
        <el-input v-model="formData.mobile" placeholder="联系方式" style="width: 200px"
          :disabled="!judgeCanEdit(formData.status)" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="回收垃圾的大约情况等等" type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }" resize="none" :disabled="!judgeCanEdit(formData.status)" />
      </el-form-item>
      <el-form-item label="驳回原因" prop="rejectReason" v-show="formData.status == '4'">
        <el-input v-model="formData.rejectReason" placeholder="驳回原因" type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }" resize="none" :disabled="!judgeCanEdit(formData.status)" />
      </el-form-item>
      <el-form-item label="取消原因" prop="cancelReason" v-show="judgeCanSeeCancel(formData.status)">
        <el-input v-model="formData.cancelReason" placeholder="取消原因" type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }" resize="none"
          :disabled="formData.status == '5' || formData.status == '6' || formData.status == '8'" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="danger" @click="applyCancelRequest()" v-show="judgeCanCancel(formData.status)">
          取消申请
        </el-button>
        <el-button type="primary" @click="handleSubmit()" v-show="judgeCanEdit(formData.status)">
          提交
        </el-button>
        <el-button type="primary" v-if="formData.status == '6'" @click="handleSubmit()">
          回退确认
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!--历史处理记录弹框-->
  <HistoryRecordList ref="historyRecordListRef"></HistoryRecordList>
  <!--范围筛选弹框-->
  <el-dialog v-model="filterDialog.visible" :title="filterDialog.title" width="500px"
    @close="handleCloseFilterDialog()">
    <el-form ref="filterFormRef" :model="filterForm" label-width="100px">
      <el-form-item label="申请状态" prop="status">
        <el-select v-model="filterForm.status" placeholder="全部" style="width: 150px">
          <el-option v-for="item in RecycleStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" prop="createTime">
        <el-date-picker v-model="filterForm.createTimeRange" type="datetimerange" placeholder="请选择"
          format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" range-separator="至" start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="期望收益" prop="expectReturn">
        <el-input-number v-model="filterForm.minExpectReturn" :precision="2" :step="0.1" placeholder="最小值"
          style="width: 160px">
          <template #suffix>元</template>
        </el-input-number>
        <span style="margin:0 5px"></span>
        <el-input-number v-model="filterForm.maxExpectReturn" :precision="2" :step="0.1" placeholder="最大值"
          style="width: 160px">
          <template #suffix>元</template>
        </el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <div style="text-align:center">
        <el-button @click="resetHandleFilter()">重置</el-button>
        <el-button type="primary" @click="handleFilter()">应用</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
defineOptions({
  name: "RecycleRequest",
  inheritAttrs: false,
});

import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { RecycleStatusOptions } from "@/enums/RecycleStatusEnum.ts";
import RecycleRequestAPI, { RecycleQueryParams, WasteItem } from "@/api/system/recycle-request.ts";
import FileAPI from "@/api/file";
import { pcaTextArr } from "element-china-area-data";
import HistoryRecordList from "@/components/HistoryRecordList/index.vue";

const formLoading = ref(false);
const historyRecordListRef = ref(null)
//表单数据
const dataFormRef = ref();
const dataFormRules = ref({
  address: [
    { required: true, message: '请选择回收地址', trigger: 'blur' }
  ],
  recycleTime: [
    { required: true, message: '请选择预约时间', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (value) {
          const selectedTime = new Date(value).getTime();
          const currentTime = new Date().getTime();

          // 预约时间必须大于当前时间
          if (selectedTime <= currentTime) {
            callback(new Error('预约时间必须大于当前时间'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ],
  mobile: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  remark: [
    { required: false, trigger: 'blur' }
  ],
  rejectReason: [
    {
      required: true, message: '请输入驳回原因', trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (formData.status === '4' && !value) {
          callback(new Error('驳回原因不能为空'));
        } else {
          callback();
        }
      }
    }
  ],
  cancelReason: [
    {
      required: true, message: '请输入取消原因', trigger: 'blur',
      validator: (rule: any, value: any, callback: any) => {
        if (judgeCanCancel(formData.status) && !value) {
          callback(new Error('取消原因不能为空'));
        } else {
          callback();
        }
      }
    }
  ]
});
const formData = reactive({
  id: "",
  area: [], //包含省市区
  address: "",
  recycleTime: "",
  mobile: "",
  expectReturn: 0.0,
  remark: "",
  status: "",
  cancelReason: "",
  rejectReason: "",
  wasteList: [] as WasteItem[], // 指定数组类型
});

const rules = ref({});

//发起申请弹框
const dialog = reactive({
  title: "",
  visible: false,
});
//打开申请弹框
const wasteTypesOptions = ref();
const handleOpenDialog = async (id?: number) => {
  wasteTypesOptions.value = await RecycleRequestAPI.getAllWasteTypes();
  if (id) {
    formLoading.value = true;
    dialog.title = "修改申请";
    //查询回写
    const data = await RecycleRequestAPI.getRecycleRequestForm(id);
    Object.assign(formData, data);
    formLoading.value = false;
  } else {
    dialog.title = "发起申请";
  }
  dialog.visible = true;
};
//关闭申请弹框
const handleCloseDialog = () => {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = "";
  formData.area = [];
  formData.address = "";
  formData.mobile = ""
  formData.status = "";
  formData.remark = "";
  formData.expectReturn = 0.0;
  formData.cancelReason = "";
  formData.rejectReason = "";
  formData.wasteList = [];

  getPage();
};

// 取消申请弹框
const handleCancelDialog = () => {
  //TODO 批量删除上传的图片，如果是新增（取消），修改（取消，删除新添动了图片列表）
  // if (formData.wasteList.length > 0) {
  //   formData.wasteList.forEach((item: any) => {
  //     if (item.fileUrl) {
  //       FileAPI.delete(item.fileUrl);
  //     }
  //   });
  // }
  handleCloseDialog();
};
//提交申请表单
const handleSubmit = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      //主表id
      const id = formData.id;
      if (id) {
        RecycleRequestAPI.updateUserRecycleRequest(formData).then(() => {
          ElMessage.success("修改成功");
          handleCloseDialog();
        });
      } else {
        RecycleRequestAPI.initUserRecycleRequest(formData).then(() => {
          ElMessage.success("申请成功");
          handleCloseDialog();
        });
      }
    }
  });
};

//申请取消
const applyCancelRequest = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      RecycleRequestAPI.applyCancelRequest(formData).then(() => {
        ElMessage.success("申请成功");
        handleCloseDialog();
      });
    }

  })
}
/**
 * 垃圾列表管理
 */
const addWasteItem = () => {
  const newWasteItem: WasteItem = {
    id: "",
    typeId: "",
    fileUrl: "",
    weight: undefined,
    actualPrice: 0.0,
  };

  formData.wasteList.push(newWasteItem);
};
const deleteWasteItem = async (index: number) => {
  if (formData.wasteList[index].fileUrl) {
    await FileAPI.delete(formData.wasteList[index].fileUrl);
  }
  formData.wasteList.splice(index, 1);
};

/**
 * 查询申请分页数据
 */
const pageKeys = ref<string[]>([]);
const pageData = ref([]);
const queryParams = reactive<RecycleQueryParams>({
  pageNum: 1,
  pageSize: 10,
});

const getPage = () => {
  RecycleRequestAPI.getRecycleRequestPage(queryParams).then((data) => {
    pageKeys.value = Object.keys(data);
    Array.from(pageKeys.value).forEach((key) => {
      pageData.value[key] = data[key];
    });
  });
};

//获取垃圾列表中第一个fileUrl非空的url
const getFirstUrl = (list: any) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].fileUrl) {
      return list[i].fileUrl;
    }
  }
};

//根据状态status判断是否可编辑
const judgeCanEdit = (status: any) => {
  if (status == '' || status == 0 || status == 4) {
    return true;
  } else {
    return false;
  }
};
const judgeCanCancel = (status: any) => {
  if (status != '' && (status == 0 || status == 1 || status == 2)) {
    return true;
  } else {
    return false;
  }
}
const judgeCanSeeCancel = (status: any) => {
  if (status != '' && (status == 0 || status == 1 || status == 2 || status == 5 || status == 6)) {
    return true;
  } else {
    return false;
  }
}
/**
 * 历史处理记录
 */
const openHistoryRecord = (requestId: any) => {
  historyRecordListRef.value?.openHistoryDialog(requestId);
};

/**
 * 筛选框
 */
const filterDialog = reactive({
  visible: false,
  title: "筛选",
});
const filterFormRef = ref();
const filterForm = reactive({
  createTimeRange: [],
  status: "",
  minExpectReturn: undefined,
  maxExpectReturn: undefined
})
const handleOpenFilterDialog = () => {
  //TODO 筛选框
  filterDialog.visible = true;
};
const handleCloseFilterDialog = () => {
  filterDialog.visible = false;
}
/**
 * 应用筛选
 */
const handleFilter = () => {
  queryParams.status = filterForm.status;
  queryParams.createTimeStart = filterForm.createTimeRange[0];
  queryParams.createTimeEnd = filterForm.createTimeRange[1];
  queryParams.minExpectReturn = filterForm.minExpectReturn;
  queryParams.maxExpectReturn = filterForm.maxExpectReturn;
  RecycleRequestAPI.getRecycleRequestPage(queryParams).then((data) => {
    pageKeys.value = Object.keys(data);
    Array.from(pageKeys.value).forEach((key) => {
      pageData.value[key] = data[key];
    });
    handleCloseFilterDialog();
  });
}
const resetHandleFilter = () => {
  filterForm.status = "";
  filterForm.createTimeRange = [];
  filterForm.minExpectReturn = undefined;
  filterForm.maxExpectReturn = undefined;
  handleFilter();
}
onMounted(() => {
  getPage();
});
</script>
<style scoped lang="scss">
.button_group {
  margin: 5px 10%;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.request_group_list {
  margin: 20px 10%;
  padding: 20px;
  background: linear-gradient(to bottom, #f8f9fa, #ffffff);
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

  :deep(.el-timeline) {
    padding: 0;

    .el-timeline-item__timestamp {
      font-size: 1.2em;
      color: var(--el-color-primary);
      font-weight: 500;
      margin-bottom: 15px;
    }

    .el-timeline-item__node {
      background-color: var(--el-color-primary);
      border: 2px solid var(--el-color-primary-light-5);
      box-shadow: 0 0 8px var(--el-color-primary-light-3);
    }
  }

  .el-card {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    border: none;
    overflow: hidden;

    &:hover {
      transform: translateY(-8px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
    }

    :deep(.el-card__header) {
      background: linear-gradient(135deg, var(--el-color-primary-light-7), var(--el-color-primary-light-9));
      color: var(--el-color-primary-dark-2);
      padding: 15px 20px;
      font-weight: 500;
      border-bottom: none;

      span {
        color: var(--el-color-primary);
        font-size: 1.2em;
        font-weight: 600;
      }
    }

    :deep(.el-card__body) {
      padding: 20px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background-color: #fff;

      .el-image {
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        transition: transform 0.3s ease;

        &:hover {
          transform: scale(1.02);
        }
      }
    }

    :deep(.el-card__footer) {
      background-color: #f8f9fa;
      padding: 12px 20px;
      border-top: 1px solid #f0f0f0;

      .el-tag {
        font-weight: 500;
        border-radius: 4px;
        padding: 6px 12px;
        font-size: 0.9em;
      }

      .el-link {
        font-weight: 500;

        &:hover {
          opacity: 0.8;
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 12px;
  padding-top: 10px;
}

:deep(.el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);

  .el-dialog__header {
    background: linear-gradient(to right, var(--el-color-primary-light-5), var(--el-color-primary-light-7));
    margin: 0;
    padding: 15px 20px;

    .el-dialog__title {
      color: #fff;
      font-weight: 500;
    }
  }

  .el-dialog__body {
    padding: 20px 30px;
  }

  .el-form-item {
    margin-bottom: 20px;
  }

  .el-input,
  .el-select,
  .el-cascader,
  .el-date-picker {
    width: 100%;
    max-width: 400px;
  }

  .el-textarea {
    width: 100%;
  }
}
</style>
